use std::time::Duration;

use serde::Deserialize;
use tokio::time;

use crate::components;
use crate::runtime::response::MagicBoxResponse;
use crate::runtime::result::MagicBoxResult;

#[derive(Debug, Default, Clone, Deserialize)]
pub(crate) enum Action {
    #[default]
    Start,
    Restart,
    Stop,
    Upgrade,
    Uninstall,
}

#[tauri::command(rename_all = "snake_case")]
pub(crate) async fn invoke_component_v2ray_action(action: Action) -> MagicBoxResult<MagicBoxResponse<()>> {
    match action {
        Action::Start => components::v2ray::manager::manager().start()?,
        Action::Restart => {
            components::v2ray::manager::manager().stop()?;
            time::sleep(Duration::from_millis(1000)).await;
            components::v2ray::manager::manager().start()?;
        }
        Action::Stop => components::v2ray::manager::manager().stop()?,
        Action::Upgrade => component_v2ray_upgrade()?,
        Action::Uninstall => components::v2ray::manager::manager().uninstall()?,
    };

    Ok(MagicBoxResponse::new_empty_success())
}

fn component_v2ray_upgrade() -> MagicBoxResult<()> {
    Ok(())
}